package com.lcxw.hxzbapi.common;

import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response validationBodyException(MethodArgumentNotValidException exception) {

        Response response = new Response();

        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {

            List<ObjectError> errors = result.getAllErrors();
            Map<String, String> data = new HashMap<String, String>();

            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                data.put(fieldError.getField(), fieldError.getDefaultMessage());
            });
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("invalid requestParam");
            response.setData(data);
            logger.error("请求参数校验不通过 " + data.toString().replaceAll("=", ":"));
        }
        return response;
    }
}